package com.agileai.bpm.servlet;

import java.util.HashMap;
import java.util.List;

import com.agileai.bpm.bizmoduler.resource.VarDefineManage;
import com.agileai.bpm.bizmoduler.resource.WfDbconfigManage;
import com.agileai.bpm.interceptor.PropertiesResourceManager;
import com.agileai.bpm.service.running.ProcessEngine;
import com.agileai.common.AppConfig;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.hotweb.database.OracleClobConverter;
import com.agileai.hotweb.servlet.DispatchServlet;

public class ManageServlet extends DispatchServlet{
	private static final long serialVersionUID = -2062201895727509143L;

	protected void initResource(){
		super.initResource();
		
		initPropertiesConfig();
		initDataSources();
		
		BeanFactory beanFactory = BeanFactory.instance();		
		AppConfig appConfig = beanFactory.getAppConfig();
		boolean handleOracleClob = appConfig.getBoolConfig("GlobalConfig", "HandleOracleClob");
		if (handleOracleClob){
			OracleClobConverter oracleClobConverter = new OracleClobConverter();
			DataRow.addGlobalConvert("WFP_DEFINE",oracleClobConverter);
			DataRow.addGlobalConvert("WFP_GRAPH",oracleClobConverter);
			DataRow.addGlobalConvert("WFE_CONTENT",oracleClobConverter);
			DataRow.addGlobalConvert("WFHA_ATTRIBUTES",oracleClobConverter);
			DataRow.addGlobalConvert("WFIA_ATTRIBUTES",oracleClobConverter);
			DataRow.addGlobalConvert("WFIFV_VARVALUE",oracleClobConverter);
		}
		
		ProcessEngine processEngine = (ProcessEngine)beanFactory.getBean("processEngine");
		processEngine.initialize();
	}
	
	private void initPropertiesConfig(){
		try {
			PropertiesResourceManager manager = PropertiesResourceManager.instance();
			VarDefineManage varDefineManageService = (VarDefineManage)BeanFactory.instance().getBean("varDefineManageService");
			
			List<DataRow> masterRecords = varDefineManageService.findMasterRecords(new DataParam());
			HashMap<String,List<DataRow>> entries = varDefineManageService.queryEntryRecords();
			manager.init(masterRecords, entries);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initDataSources(){
		WfDbconfigManage dbConfigManageService = (WfDbconfigManage)BeanFactory.instance().getBean("wfDbconfigManageService");
		dbConfigManageService.initializeDataSources();
	}
}
